import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_module/api/cooperation_request.dart';
import 'package:flutter_module/common/base/base_page.dart';
import 'package:flutter_module/common/utils/object_to_any.dart';
import 'package:flutter_module/model/service_object_mo.dart';
import 'package:flutter_module/page/base/base_view.dart';
import 'package:flutter_module/page/service_provider_edit/widgets/GridViewItemWidget.dart';
import 'package:flutter_module/style/colors.dart';

/// 合作服务商服务对象
class ServiceProviderEditServiceObjectPage extends BaseStateFulWidget {
  ServiceProviderEditServiceObjectPage({required this.params});

  final Map params;

  @override
  BaseState<StatefulWidget> buildState() {
    return _ServiceProviderEditServiceObjectState();
  }
}

class _ServiceProviderEditServiceObjectState
    extends BaseState<ServiceProviderEditServiceObjectPage> with BasePage {
  List<ServiceObjectMo> serviceObjectList = [];
  List<String> targetCodeNameList = [];
  List<String> targetCodeList = [];

  @override
  void initState() {
    super.initState();
    targetCodeNameList = widget.params["targetCodeName"] ?? [];
    _getCooperationDetails();
  }

  @override
  String get appBarTitle => "服务对象";

  @override
  getActions() {
    return [
      new TextClickView(
        title: "保存",
        isTitleRight: true,
        rightClick: () {
          Navigator.of(context).pop({
            'targetCodeName': targetCodeNameList,
            'targetCode': targetCodeList,
          });
        },
      )
    ];
  }

  @override
  Widget createView(
    BuildContext context,
  ) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 16, right: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            child: Text(
              "请选择您服务的对象（已添加${targetCodeNameList.length}个）",
              style: TextStyle(color: ThemeColors.text333, fontSize: 12),
            ),
            padding: const EdgeInsets.only(bottom: 14.0, top: 14.0),
          ),
          Expanded(
            child: Container(
              child: _getGridView(),
              padding: const EdgeInsets.only(left: 14.0, right: 14.0),
            ),
          )
        ],
      ),
    );
  }

  _getGridView() {
    return GridView.builder(
      physics: new NeverScrollableScrollPhysics(),
      //子Item的个数
      itemCount: serviceObjectList.length,
      //子布局构建器
      itemBuilder: (BuildContext context, int index) {
        //取出每个数据
        ServiceObjectMo bean = serviceObjectList[index];

        return GridViewItemWidget(
            bean: bean,
            callback: () {
              targetCodeNameList.clear();
              targetCodeList.clear();
              serviceObjectList.forEach((ServiceObjectMo element) {
                //选中标识
                if (element.nativeSelect!) {
                  targetCodeList.add(element.dictCode!);
                  targetCodeNameList.add(element.dictName!);
                }
              });
              setState(() {});
            });
      },
      //子布局排列方式
      //按照固定列数来排列
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        //主方向的Item间隔 竖直方向
        mainAxisSpacing: 8,
        //次方向的Item间隔
        crossAxisSpacing: 8,
        //子Item 的宽高比
        childAspectRatio: 100 / 28,
        //每行3列
        crossAxisCount: 3,
      ),
    );
  }

  //请求获取合作服务商详情
  void _getCooperationDetails() async {
    DicListRequest request = new DicListRequest();
    request.addQurey("dicType", "SERVICE_PROVIDER");
    try {
      var result = await request.fire(this);
      serviceObjectList =
          object2list(result).map((e) => ServiceObjectMo.fromJson(e)).toList();

      targetCodeNameList.forEach((selectElement) {
        serviceObjectList.forEach((element) {
          if (selectElement == element.dictName) {
            element.nativeSelect = true;
          }
        });
      });
      isLoading = false;
      setState(() {});
    } catch (e) {
      print("error: $e");
    }
  }
}
